package com.yanqu.road.web.mgr;

import com.yanqu.data.analytics.Provider;
import com.yanqu.data.analytics.ProviderFactory;
import com.yanqu.data.analytics.constant.EventDataConstants;
import com.yanqu.data.analytics.enums.eUserAttr;
import com.yanqu.data.analytics.helper.DataBuilder;
import com.yanqu.data.analytics.impl.EmptyProvider;
import com.yanqu.road.entity.enums.eChannelType;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.recharge.RechargeOrder;
import com.yanqu.road.entity.servercenter.ChannelInfo;
import com.yanqu.road.entity.servercenter.DAServerInfo;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.manger.DAServerListMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.WebServer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class WebDataAnalyticsMgr extends TempMgr {

    private static Logger logger = LogManager.getLogger(WebDataAnalyticsMgr.class.getName());

    public static Provider provider = new EmptyProvider(logger);

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        if (WebServer.getInstance().isUserCenter()) {
            // 用户中心不需要初始化了
            return true;
        }

        ServerInfo serverInfo = ServerListMgr.getServerInfo(ConfigHelper.getInt("serverId"));
        if(serverInfo == null){
            return false;
        }
        ChannelInfo channelInfo = ServerListMgr.getChannelInfo(serverInfo.getChannelId());
        if(channelInfo == null){
            return false;
        }
        //渠道
        if(initDataAnalytics()) {
            if(channelInfo.getKafkaCollect() == 1){
                provider = ProviderFactory.getProvider("KAFKA", logger, null);
            }else if(!StringUtils.isNullOrEmpty(channelInfo.getCollectServerUrl())) {
                provider = ProviderFactory.getProvider("TDA", logger, channelInfo.getCollectServerUrl());
            }
        }else {
            Provider old = provider;
            provider = new EmptyProvider(logger);
            old.flush();
        }
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        if(provider != null) {
            provider.flush();
            provider.close();
        }
        return true;
    }

    /**
     * 定时发送
     */
    public static void flush(){
        if(provider != null){
            provider.flush();
        }
    }

    /**
     * 是否开启埋点
     */
    public static boolean openDataAnalytics(){
        if(provider.getClass().getSimpleName().equals("EmptyProvider")){
            return false;
        }
        return true;
    }

    /**
     * 是否初始化埋点
     */
    private static boolean initDataAnalytics(){
        ServerInfo serverInfo = ServerListMgr.getServerInfo(ConfigHelper.getLong("serverId"));
        if(serverInfo == null){
            return false;
        }
        ChannelInfo channelInfo = ServerListMgr.getChannelInfo(serverInfo.getChannelId());
        if(channelInfo == null){
            return false;
        }
        if(!channelInfo.isOpenDataAnalytics()){
            return false;
        }
        if(StringUtils.isNullOrEmpty(channelInfo.getCollectServerUrl())){
            return false;
        }
        DAServerInfo daServerInfo = DAServerListMgr.get(channelInfo.getChannelId(), serverInfo.getServerId());
        if(daServerInfo == null){
            return false;
        }
        return true;
    }

    /**
     * 获取访客ID
     */
    public static String getDistinctId(UserInfo userInfo){
        return "";
    }

    /**
     * 账号注册埋点
     */
    public static void createCount(UserInfo userInfo) {
        try {
            if (!openDataAnalytics()) return;

            DataBuilder builder = DataBuilder.newBuilder(userInfo.getUserId() + "", getDistinctId(userInfo));
            long serverId = ConfigHelper.getInt("serverId");
            ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);
            //openId
            builder.build(eUserAttr.OPEN_ID.getAttrId(), userInfo.getOpenId());
            //区服id
            builder.build(eUserAttr.SERVER_ID.getAttrId(), serverId);
            if(serverInfo != null){
                builder.build(eUserAttr.SERVER_NAME.getAttrId(), serverInfo.getServerName());
                builder.build(eUserAttr.CHANNEL_ID.getAttrId(), serverInfo.getChannelId());
                builder.build(eUserAttr.SERVER_TIME.getAttrId(), DateHelper.getCurrentDateTimeString(serverInfo.getOpenTime() * 1000));

                eChannelType channelType = eChannelType.forValue(serverInfo.getChannelId());
                if(channelType != null){
                    builder.build(eUserAttr.CHANNEL.getAttrId(), channelType.getName());
                }
            }
            if(!StringUtils.isNullOrEmpty(userInfo.getPlatformUserId())){
                builder.build(eUserAttr.PLATFORM_ID.getAttrId(), userInfo.getPlatformUserId());
            }
            if(userInfo.getUserId() > 0){
                builder.build(eUserAttr.USERID_ID.getAttrId(), userInfo.getUserId());
            }
            builder.build(eUserAttr.USERALIAS_ID.getAttrId(), userInfo.getUserAliasId());

            builder.build(eUserAttr.CREATE_ACCOUNT_TIME.getAttrId(), DateHelper.getCurrentDateTimeString());
            provider.user_setOnce(builder.getAccountId(), builder.getDistinctId(), builder.getDataMap());

            //注册事件
            DataBuilder registerBuilder = DataBuilder.newBuilder(userInfo.getUserId(), getDistinctId(userInfo));
            provider.track(registerBuilder.getAccountId(), registerBuilder.getDistinctId(), EventDataConstants.Base.REGISTER, registerBuilder.getDataMap());
        }catch (Exception e){
            logger.error("analytics createCount error ", e);
        }
    }


    public static void initOrder(RechargeOrder rechargeOrder) {
        try {
            if (!openDataAnalytics()) return;

        }catch (Exception e){
            logger.error("error ", e);
        }
    }
}
